package leetcode.t2String;

/**
 * 5. 最长回文子串
 * 中心扩散查询，奇偶都需要查
 *
 * @author K
 * @date 2024/1/23 14:34
 */
public class T5_LongestPalindrome {

    public static String longestPalindrome(String s) {
        String res = "";
        for (int i = 0; i < s.length(); i++) {
            String s1 = dp(s, i, i + 1);
            String s2 = dp(s, i, i);
            if (s1.length() > res.length()) res = s1;
            if (s2.length() > res.length()) res = s2;
        }
        return res;
    }

    public static String dp(String s, int left, int right) {
        while (left <= right && left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        return s.substring(left + 1, right);
    }

    public static String longestPalindrome1(String s) {
        if (s == null || s.length() < 1) {
            return "";
        }
        int start = 0, end = 0;
        for (int i = 0; i < s.length(); i++) {
            Integer length = find(s, i, i);
            Integer length2 = find(s, i, i + 1);
            Integer len = Math.max(length2, length);
            if (len > end - start) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }

        return s.substring(start, end + 1);
    }


    public static Integer find(String s, Integer left, Integer right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        return right - left - 1;
    }


    public static void main(String[] args) {
        String result = longestPalindrome("babad");
        String result1 = longestPalindrome("cbbd");
        System.out.println();
    }

}
